package com.sharding5.multi.mybatis.seata.config;

import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceBuilder;
import io.seata.rm.datasource.DataSourceProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author lenovo
 */
@Slf4j
@Configuration
@MapperScan(basePackages = "com.sharding5.multi.mybatis.seata.mapper.store", sqlSessionTemplateRef = "storeSqlSessionTemplate")
public class StoreDbConfig {
    @Bean(name = "storeDataSource")
    @ConfigurationProperties("spring.datasource.druid.store")
    public DataSource storeDataSource() {
        log.info("初始化 store 数据源");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "storeDataSourceProxy")
    public DataSourceProxy storeDataSourceProxy(@Qualifier("storeDataSource") DataSource storeDataSource) {
        // DataSourceProxy proxy = new DataSourceProxy(storeDataSource,"my_test_tx_group");
        DataSourceProxy proxy = new DataSourceProxy(storeDataSource, "DEFAULT");
        return proxy;
    }

    @Bean(name = "storeSqlSessionFactory")
    public SqlSessionFactory storeSqlSessionFactory(@Qualifier("storeDataSourceProxy") DataSource storeDataSourceProxy) throws Exception {
        // 使用 MyBatis 时
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        // 使用 MyBatis-Plus 时
        // MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(storeDataSourceProxy);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/store/*.xml"));
        return bean.getObject();
    }

    @Bean("storeTransactionManager")
    public DataSourceTransactionManager storeTransactionManger(@Qualifier("storeDataSourceProxy") DataSource storeDataSourceProxy) {
        return new DataSourceTransactionManager(storeDataSourceProxy);
    }

    @Bean(name = "storeSqlSessionTemplate")
    public SqlSessionTemplate storeSqlSessionTemplate(@Qualifier("storeSqlSessionFactory") SqlSessionFactory storeSqlSessionFactory) {
        return new SqlSessionTemplate(storeSqlSessionFactory);
    }
}